package common

import (
	"encoding/json"
	"fmt"
	"github.com/idoubi/goz"
	"github.com/spf13/viper"
	"log"
	"time"
)

const (
	TokenUrl       = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential"
	AuthorizeUrl   = "https://open.weixin.qq.com/connect/oauth2/authorize"
	RedirectUri    = "https://xcx2.6jiehui.top/beeorder/goods/test"
	AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token"
	UserInfoUrl    = "https://api.weixin.qq.com/sns/userinfo"
	TicketUrl      = "https://api.weixin.qq.com/cgi-bin/ticket/getticket"
)

func GetAccessToken() interface{} {
	accessToken, err := GetRedis().Get("ACCESS_TOKEN").Result()
	if len(accessToken) > 0 {
		return accessToken
	}
	appid := viper.GetString("wx.appid")
	AppSecret := viper.GetString("wx.AppSecret")
	cli := goz.NewClient()
	var url = TokenUrl + "&appid=" + appid + "&secret=" + AppSecret
	resp, err := cli.Get(url)
	if err != nil {
		log.Fatalln(err)
	}
	content, err := resp.GetBody()
	if err != nil {
		log.Fatalln(err)
	}
	var result = map[string]interface{}{}
	err = json.Unmarshal(content, &result)
	if err != nil {
		return err.Error()
	}

	if _, ok := result["access_token"]; ok {
		cmd, _ := GetRedis().Set("ACCESS_TOKEN", result["access_token"], time.Second*7200).Result()
		fmt.Println(cmd)
	}

	return result["access_token"]
}

func GetAuthorizeUrl() string {

	appid := viper.GetString("wx.appid")
	var url = AuthorizeUrl + "?appid=" + appid + "&redirect_uri=" + RedirectUri + "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect"
	return url
}

func CodeChangeAccessToken(code string) map[string]string {
	appid := viper.GetString("wx.appid")
	AppSecret := viper.GetString("wx.AppSecret")
	var url = AccessTokenUrl + "?appid=" + appid + "&secret=" + AppSecret + "&code=" + code + "&grant_type=authorization_code"
	cli := goz.NewClient()
	resp, err := cli.Get(url)
	if err != nil {
		log.Fatalln(err)
	}
	content, err := resp.GetBody()
	if err != nil {
		log.Fatalln(err)
	}
	var result = map[string]string{}
	err = json.Unmarshal(content, &result)
	if err != nil {
		fmt.Println(err)
	}
	return result
}

type userInfo struct {
	Openid    string `json:"openid"`
	Nick      string `json:"nickname"`
	AvatarUrl string `json:"headimgurl" gorm:"column:avatarUrl"`
	Country   string `json:"country"`
	City      string `json:"city"`
	Province  string `json:"province"`
	Gender    int    `json:"sex"`
}
type UserCreate struct {
	userInfo
}

func OpenidGetUserinfo(data map[string]string) userInfo {
	var url = UserInfoUrl + "?access_token=" + data["access_token"] + "&openid=" + data["openid"] + "&lang=zh_CN"
	cli := goz.NewClient()
	resp, err := cli.Get(url)
	if err != nil {
		log.Fatalln(err)
	}
	content, err := resp.GetBody()
	fmt.Println("content=", content)
	if err != nil {
		log.Fatalln(err)
	}
	var result = userInfo{}
	err = json.Unmarshal(content, &result)
	if err != nil {
		fmt.Println("json转化失败：", err)
	}
	return result
}

type TicketStruct struct {
	Errcode   int    `json:"errcode"`
	Errmsg    string `json:"errmsg"`
	Ticket    string `json:"ticket"`
	ExpiresIn int    `json:"expires_in"`
}

// GetTicket 获取票据
func GetTicket() (int, string) {
	TICKET, _ := GetRedis().Get("TICKET").Result()
	if len(TICKET) > 0 {
		return 0, TICKET
	}
	AccessToken := GetAccessToken()
	fmt.Println("AccessToken=", AccessToken)
	var url = TicketUrl + "?type=jsapi&access_token=" + AccessToken.(string)
	content := CurlGet(url)
	var result = TicketStruct{}
	err := json.Unmarshal(content, &result)
	if err != nil {
		return result.Errcode, result.Errmsg
	}
	if result.Ticket != "" {
		cmd, _ := GetRedis().Set("TICKET", result.Ticket, time.Second*7200).Result()
		fmt.Println(cmd)
	}
	return result.Errcode, result.Ticket
}

// WXTextMsg 微信文本消息结构体
type WXTextMsg struct {
	ToUserName   string
	FromUserName string
	CreateTime   int64
	MsgType      string
	Content      string
	MsgId        int64
}
